//
//  TCSpecialTopicViewController.m
//  Project_B
//
//  Created by dllo on 15/11/24.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "TCSpecialTopicViewController.h"
#import "TCSpecialTopicCollectionViewCell.h"
#import "TCMyThirdTableViewCell.h"
#import "TCMyTableViewCell.h"
#import "TCMySecondTableViewCell.h"
#import "AFNetworkHandler.h"
#import "TCRoute.h"
#import "TCTopic.h"
#import "TCspecial.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "TCRouteViewController.h"
#import "TCTopicViewController.h"
#import "TCSpecialHotTopicViewController.h"
#import "RESideMenu.h"
#import "FirstSpecialTableViewCell.h"
#import "FirstTopViewViewController.h"
#import "FirstColumnViewController.h"
#import "ColumnTableViewCell.h"
#import "FirstSpecialViewController.h"
#import "LocalAuthentication/LAContext.h"
#import "UIImage+GIF.h"
#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface TCSpecialTopicViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)NSArray *arr;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, assign)NSInteger differentiate;
@property (nonatomic, strong)NSMutableArray *webArr;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *routeArr;
@property (nonatomic, strong)NSMutableArray *topicArr;
@property (nonatomic, strong)NSMutableArray *specialArr;
@property (nonatomic, assign) NSInteger i;
@property (nonatomic, assign) NSInteger j;
@property (nonatomic, assign) NSInteger k;
@property (nonatomic, strong)MBProgressHUD *HUD;
@property (nonatomic, strong)UIButton *button;
@end

@implementation TCSpecialTopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    
    
#if 0
//指纹识别
    LAContext *myContext = [[LAContext alloc] init];
    NSError *authError = nil;
    NSString *myLocalizedReasonString = @"请输入指纹";
    if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
        [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                  localizedReason:myLocalizedReasonString
                            reply:^(BOOL success, NSError *error) {
                                if (success) {
                            // User authenticated successfully, take appropriate action
                                   
                                } else {
                                   
                                    // User did not authenticate successfully, look at error and take appropriate action
                                }
                            }];
        
    } else {
        
        // Could not evaluate policy; look at authError and present an appropriate message to user
        
    }
#endif
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-category"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.webArr = [NSMutableArray array];
    self.routeArr = [NSMutableArray array];
    self.topicArr = [NSMutableArray array];
    self.specialArr = [NSMutableArray array];
    NSString *strRoute = @"http://api.lis99.com/v3/club/clubtopics/0/";
    [self.webArr addObject:strRoute];
    NSString *strHot = @"http://api.lis99.com/v3/club/hottopics/0/";
    [self.webArr addObject:strHot];
    NSString *strSpecial = @"http://api.lis99.com/v3/club/zhuanti/0/";
    [self.webArr addObject:strSpecial];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    [self creatNaviTitle];
    [self getData];
    

    self.i = 0;
    self.j = 0;
    self.k = 0;
    self.button = [[UIButton alloc]initWithFrame:CGRectMake(330, 500, 30, 30)];

}
- (void)creatCollection
{
    UICollectionViewFlowLayout *Layout = [[UICollectionViewFlowLayout alloc]init];
    Layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    Layout.itemSize = CGSizeMake(WIDTH, HEIGHT);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:Layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    Layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    Layout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[TCSpecialTopicCollectionViewCell class] forCellWithReuseIdentifier:@"myitem"];
}
- (void)getData
{
    [AFNetworkHandler getUrl:self.webArr[0] cookie:nil result:^(id result) {
        self.routeArr = [TCRoute transformWithArray:result[@"data"][@"clubtopiclist"]];
        [self.tableView reloadData];
        }];
    [AFNetworkHandler getUrl:self.webArr[1] cookie:nil result:^(id result) {
        self.topicArr = [TCTopic transformWithArray:result[@"data"][@"topicslist"]];
        [self.tableView reloadData];
        }];
    [AFNetworkHandler getUrl:self.webArr[2] cookie:nil result:^(id result) {
        self.specialArr = [TCspecial transformWithArray:result[@"data"][@"omnibuslist"]];
        [self.tableView reloadData];
        [self.HUD hide:YES];
        }];
    [self creatCollection];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.mode = MBProgressHUDModeIndeterminate;

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (void)setupRefreshRoute
{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf prepareRootActivityData];
    }];
//    self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(prepareRootActivityData)];
}
- (void)prepareRootActivityData
{
    self.i++;
    NSString *str = [NSString stringWithFormat:@"http://api.lis99.com/v3/club/clubtopics/%ld", self.i];
    [AFNetworkHandler getUrl:str cookie:nil result:^(id result) {
    [self.routeArr addObjectsFromArray:[TCRoute transformWithArray:result[@"data"][@"clubtopiclist"]]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpHotData
{
    self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(prepareHotData)];
}
- (void)prepareHotData
{
    self.j++;
    NSString *str = [NSString stringWithFormat: @"http://api.lis99.com/v3/club/hottopics/%ld/", self.j];
    [AFNetworkHandler getUrl:str cookie:nil result:^(id result) {
        [self.topicArr addObjectsFromArray:[TCTopic transformWithArray:result[@"data"][@"topicslist"]]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpSpecialData
{
    self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(preparespecialData)];
}
- (void)preparespecialData
{
    self.k++;
    NSString *str = [NSString stringWithFormat:@"http://api.lis99.com/v3/club/zhuanti/%ld/", self.k];
    [AFNetworkHandler getUrl:str cookie:nil result:^(id result) {
        [self.specialArr addObjectsFromArray:[TCspecial transformWithArray:result[@"data"][@"omnibuslist"]]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TCSpecialTopicCollectionViewCell *mycell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myitem" forIndexPath:indexPath];
    self.differentiate = indexPath.item;
    self.tableView = mycell.tableview;
    mycell.DataSource = self;
    mycell.Delegate = self;
    [self.tableView reloadData];
    if (indexPath.item == 0) {
        [self setupRefreshRoute];
    }
    if (indexPath.item == 1) {
        [self setUpHotData];
    }
    if (indexPath.item == 2) {
        [self setUpSpecialData];
    }
    return mycell;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.tableView.contentOffset.y > 1000) {
        self.button.backgroundColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
        self.button.layer.cornerRadius = 5;
        [self.button setBackgroundImage:[UIImage imageNamed:@"top"] forState:UIControlStateNormal];
        [self.view addSubview:self.button];
        [self.button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    }
    else
    {
        [self.button removeFromSuperview];
    }

}
- (void)action
{
    [self.tableView setContentOffset:CGPointZero animated:YES];
    [self.button removeFromSuperview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.differentiate == 0) {
    return self.routeArr.count;
    }
    if (self.differentiate == 1) {
        return self.topicArr.count;
    }
    if (self.differentiate == 2) {
        return self.specialArr.count;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.differentiate == 0) {
        TCRouteViewController *secVC = [[TCRouteViewController alloc]init];
        secVC.temp = self.routeArr[indexPath.row];
        secVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:secVC animated:YES];
    }
    if (self.differentiate == 1) {
//        TCTopicViewController *secVc = [[TCTopicViewController alloc]init];
//        secVc.temp = self.topicArr[indexPath.row];
//        secVc.navigationController.navigationBarHidden = YES;
//        secVc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:secVc animated:YES];
        FirstTopViewViewController *secVc = [[FirstTopViewViewController alloc]init];
        secVc.idString = [self.topicArr[indexPath.row] topic_id];
        secVc.typeStr = ((TCTopic *)self.topicArr[indexPath.row]).type;
        secVc.navigationController.navigationBarHidden = YES;
        secVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:secVc animated:YES];
    }
    if (self.differentiate == 2) {
//        TCSpecialHotTopicViewController *secVC = [[TCSpecialHotTopicViewController alloc]init];
//        secVC.temp = self.specialArr[indexPath.row];
//        secVC.hidesBottomBarWhenPushed = YES;
        FirstSpecialViewController *speVC = [[FirstSpecialViewController alloc] init];
        speVC.idString = [self.specialArr[indexPath.row] detailid];
        speVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:speVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.differentiate == 1) {
        return 160*(HEIGHT/667);
    } else {
        return 200*(HEIGHT/667);
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.differentiate == 0) {
    TCMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TCMyTableViewCell"];
        cell.temp = self.routeArr[indexPath.row];
    return cell;
    }
    if (self.differentiate == 1)
    {
        ColumnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TCMySecondTableViewCell"];
        cell.model = self.topicArr[indexPath.row];
        return cell;
    }
    if (self.differentiate == 2)
    {
        TCMyThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TCMyThirdTableViewCell"];
        cell.temp = self.specialArr[indexPath.row];
        return cell;
    }
    return 0;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    for (NSInteger i = 0; i < 3; i++) {
        if (self.collectionView.contentOffset.x / WIDTH == i) {
            UIButton *button = (UIButton *)[self.navigationItem.titleView viewWithTag:100 + i];
            button.titleLabel.font = [UIFont boldSystemFontOfSize:18];
            button.titleLabel.alpha = 1;
        }
        else {
            UIButton *button = (UIButton *)[self.navigationItem.titleView viewWithTag:100 + i];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            button.titleLabel.alpha = 0.5;
        }
    }
}
- (void)creatNaviTitle
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    self.navigationItem.titleView = titleView;
    self.arr = @[@"线路活动", @"最新热帖", @"全部专题"];
    for (NSInteger i = 0; i < self.arr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(WIDTH / 4 * i+1, 0, WIDTH / 3-40, 40);
        btn.tintColor = [UIColor whiteColor];
        if (i == 0) {
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
            btn.titleLabel.alpha = 1;
        } else {
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            btn.titleLabel.alpha = 0.5;
        }
        [btn setTitle:self.arr[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 100 + i;
        [titleView addSubview:btn];
    }
}
- (void)buttonAction:(UIButton *)btn
{
    [btn setShowsTouchWhenHighlighted:YES];
    for (NSInteger i = 0; i < self.arr.count; i++) {
        if (btn.tag == 100 + i) {
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
            btn.titleLabel.alpha = 1;
            self.collectionView.contentOffset = CGPointMake(WIDTH * i, 0);
        }
        if (btn.tag != 100 + i) {
            UIButton *button = (UIButton *)[self.navigationItem.titleView viewWithTag:100 + i];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            button.titleLabel.alpha = 0.5;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
